package com.spring.mvc.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import com.spring.mvc.util.FileUtil;

/**
 * HTML Mail Template
 * @author Administrator
 *
 */
public class HtmlMailTemplate implements MailTemplate {
	
	static final Logger logger=LoggerFactory.getLogger(HtmlMailTemplate.class);
	
	private MimeMessage mailMessage;
	private MimeMessageHelper helper;
	
	public HtmlMailTemplate() {
		mailMessage=new JavaMailSenderImpl().createMimeMessage();
		try {
			helper=new MimeMessageHelper(mailMessage,true);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	public HtmlMailTemplate(String to,String from,String subject){
		this();
		try {
			helper.setTo(to);
			helper.setFrom(from);
			helper.setSubject(subject);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Mail send to 
	 */
	public void setTo(String to){
		try {
			helper.setTo(to);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Mail from 
	 */
	public void setFrom(String from){
		try {
			helper.setFrom(from);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Set up Mail Theme
	 */
	public void setSubject(String subject){
		try {
			helper.setSubject(subject);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Set up Mail Context
	 */
	public void setText(String text){
		try {
			helper.setText(text,true);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Given Template Generate Mail Context
	 * @param path
	 */
	public void setTextPath(String path){
		try {
			String msg=FileUtil.readFile(path);
			if(msg!=null){
				helper.setText(msg,true);
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * return Mail Message
	 */
	public Object getMailMessage() {
		return mailMessage;
	}

}
